package com.wangp.mywrite.coding;

import cn.hutool.core.map.TableMap;
import com.google.common.collect.ImmutableList;

import java.util.*;

/**
 * @description: 2325. 解密消息
 * @author tooStronger
 * @date 2023/2/1
 */
public class DecodeMessage {

    // 第一版
    List<Character> alphabetList = Arrays.asList('a', 'b', 'c', 'd', 'e', 'f', 'g',
            'h', 'i', 'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q',
            'r', 's', 't',
            'u', 'v', 'w',
            'x', 'y', 'z');


    public String decodeMessage(String key, String message) {
        Map<Character, Character> map = new TreeMap<>();
        int listIndex = 0;
        while (map.size() != 26) {
            for (int i = 0; i < key.length(); i++) {
                char c = key.charAt(i);
                if (c != ' ' && !map.containsKey(c)) {
                    map.put(c, alphabetList.get(listIndex++));
                }
            }
        }
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < message.length(); i++) {
            char c = message.charAt(i);
            if (c == ' ') {
                res.append(c);
            } else {
                res.append(map.get(c));
            }
        }
        return res.toString();
    }

    // 优化第一版，因为 char 是可以做加法的，所以可以不用列表存储起来
    public String decodeMessage2(String key, String message) {
        Map<Character, Character> map = new HashMap<>();
        char cur = 'a';
        while (map.size() != 26) {
            for (int i = 0; i < key.length(); i++) {
                char c = key.charAt(i);
                if (c != ' ' && !map.containsKey(c)) {
                    map.put(c, cur++);
                }
            }
        }
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < message.length(); i++) {
            char c = message.charAt(i);
            if (c == ' ') {
                res.append(c);
            } else {
                res.append(map.get(c));
            }
        }
        return res.toString();
    }

    // 优化第三版，由于map占用更多内存，可以使用数组
    public String decodeMessage3(String key, String message) {
        char[] map = new char[26];
        char cur = 'a';
        for (char c : key.toCharArray()) {
            if (c != ' ' && map[c - 'a'] == 0) {
                map[c - 'a'] = cur++;
            }
        }
        char[] res = message.toCharArray();
        for (int i = 0; i < res.length; i++) {
            if (res[i] != ' ') {
                res[i] = map[res[i] - 'a'];
            }
        }
        return new String(res);
    }


    public static void main(String[] args) {
        System.out.println(new DecodeMessage().decodeMessage3("the quick brown fox jumps over the lazy dog", "vkbs bs t suepuv"));
    }
}
